package org.github.manx98.jlibhac.common.keys;

import lombok.extern.slf4j.Slf4j;
import org.github.manx98.jlibhac.crypto.AesKey;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 密匙读取器
 * @author Manx98
 * @version 1.0
 * @since 2022/10/3 0:03
 */
@Slf4j
public class ExternalKeyReader {
    public static void readKeyFile(KeySet keySet, String filename) throws IOException {
        List<KeyInfo> keyList = DefaultKeySet.createKeyList();
        try (FileInputStream reader = new FileInputStream(filename)) {
            readMainKeys(keySet, reader, keyList);
        }
    }

    public static void readMainKeys(KeySet keySet, InputStream reader, List<KeyInfo> keyList) throws IOException {
        Properties ctx = new Properties();
        ctx.load(reader);
        ctx.forEach((k, v) -> {
            SpecificKeyInfo info = tryGetKeyInfo(keyList, k.toString());
            if (info == null) {
                log.warn("Could not find specific key: {}", k);
            } else {
                AesKey key = info.Key.Getter.call(keySet, info.Index);
                if (v.toString().length() != key.Length * 2) {
                    log.warn("key {} has incorrect size {} must be {} hex digits", k, v.toString().length()
                            , key.Length * 2);
                } else {
                    key.storeFromHex(v.toString());
                }
            }
        });
    }

    private static SpecificKeyInfo tryGetKeyInfo(List<KeyInfo> keyList, String keyName) {
        for (KeyInfo keyInfo : keyList) {
            int matches = keyInfo.matches(keyName);
            if (matches > -1) {
                return new SpecificKeyInfo(keyInfo, matches);
            }
        }
        return null;
    }
}
